﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UserAuthority
{
    public class User
    {
        public enum Authority
        {
            Inquiry=1,
            Manage=2,
            Analysis=4,
            Control=8,
            auth4=16,
            aurh5=32,
            auth6=64,
            auth7=128,
        }
        private int userAuthority;
        public int UserAuthority
        {
            get { return userAuthority; }
            set { userAuthority = value; WhenAuthorityChange(); }
        }
        private string userName;
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }




        public User()
        {
            this.userName = null;
            this.userAuthority = 0;
        }
        public User(string name,int authority)
        {
            this.userName = name;
            this.userAuthority = authority;
        }

        public bool IfHasAuthority(Authority permission)
        {
            if ((userAuthority & (int)permission) != 0)
                return true;
            else
                return false;
        }

        public void AddAuthority(Authority permission)
        {
            userAuthority = userAuthority | (int)permission;
            WhenAuthorityChange();
        }

        public void RemoveAuthority(Authority permission)
        {
            userAuthority = userAuthority & (~(int)permission);
            WhenAuthorityChange();
        }
        public void ResetAuthority()
        {
            userName = null;
            userAuthority = 0;
            WhenAuthorityChange();
        }
        public void SetUser(string name,int authority)
        {
            userName = name;
            userAuthority = authority;
            WhenAuthorityChange();
        }



        //event when authority changed
        public delegate void AuthorityEventHandler(object sender, EventArgs e);
        public event AuthorityEventHandler AuthorityChanged;
        private void WhenAuthorityChange()
        {
            if (AuthorityChanged != null)
            {
                AuthorityChanged(this, null);
            }
        }

    }
}
